package notify

import (
	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/facade/httpserver"
	"gitee.com/sansaniot/ssiot-core/facade/runtime"
	"gitee.com/sansaniot/ssiot-core/httpmvc"
	"gitee.com/sansaniot/ssiot-core/httpmvc/api"
	"github.com/shafreeck/cortana"

	"ssnotify/cmd/system"
	"ssnotify/common/constant"
	"ssnotify/common/database"
	"ssnotify/common/middleware/jwt"
	"ssnotify/common/middleware/log"
	"ssnotify/common/middleware/secure"
	"ssnotify/internal/notify/router"
	"ssnotify/internal/notify/service"
)

func Start() error {
	args := struct {
		CfgFile string `cortana:"--config, -c, , config file"`
	}{}
	cortana.Parse(&args)
	if args.CfgFile != "" {
		constant.ConfigFile = args.CfgFile
	}
	// 如有需要，向内核注册自己需要的中间件
	// 限流
	httpserver.RegisterMiddlewareFunction(secure.Sentinel())
	// 自动增加requestId
	httpserver.RegisterMiddlewareFunction(secure.RequestId(httpmvc.TrafficKey))
	// 获取上下文提供的日志
	httpserver.RegisterMiddlewareFunction(api.SetRequestLogger)
	// 自定义错误处理
	httpserver.RegisterMiddlewareFunction(log.CustomError)
	// NoCache is a middleware function that appends headers
	httpserver.RegisterMiddlewareFunction(secure.NoCache)
	// 跨域处理
	httpserver.RegisterMiddlewareFunction(secure.Options)
	// Secure is a middleware function that appends security
	httpserver.RegisterMiddlewareFunction(secure.Secure)

	// 必须，初始化引擎
	httpserver.InitEngine(constant.ConfigFile)
	env.DefaultConfig.Http.Port = env.ConfigOperator.GetInt64("service.notify.port")

	// 自动检测并创建表
	database.Migrate()

	// 初始化通知服务配置
	db := runtime.Runtime.GetDbByKey("db")
	service.RefreshSettings(db)

	// 启动系统业务
	system.InitSystemBiz()

	// 可选，初始化JWT验证方法组
	jwtMiddleware, _ := jwt.AuthInit()
	// 必须，向内核注册自己的业务模块路由，如不使用中间件，则使用InitRouters方法
	httpserver.InitAuthRouters(router.RouterCheckRole, jwtMiddleware)
	httpserver.InitRouters(router.RouterNoCheckRole)
	// 启动HTTP服务器
	_ = httpserver.Run()

	return nil
}
